<?php

namespace App\Http\Middleware;

use Closure;
use Cache;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use App\Exceptions\OperateException;

class VideoAuth {

    //获取api请求地址
    protected function getUrl() {
        $url = config('video.url');
        return $url . '/api/v1/login';
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $user = $request->user();
        $uid = $user->userid;
        $isLogin = 'video_login_' . $uid;
        // Cache::forget($isLogin);
        if (Cache::get($isLogin)) {
            return $next($request);
        }
        try {
            $url = $this->getUrl();
            $client = new Client(['cookies' => true]);
            $res = $client->request('GET', $url, [
                'query' => config('video.auth')
            ]);
            $body = $res->getBody();
            $data = json_decode($body, true);

           Cache::put($isLogin, $data['Token'], now()->addSeconds($data['TokenTimeout']));
        } catch (RequestException $exception) {
            if ($exception->hasResponse()) {
                $res = $exception->getResponse();

               // var_dump($res->getStatusCode(), $res->getBody()->getContents());
                throw new OperateException(trim($res->getBody()->getContents(),'"'));
            }

        }
        return $next($request);
    }

}
